package com.meego.common.oembed;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

public class OembedXmlParser implements OembedParser {

    private final JAXBContext jaxbContext;

    public OembedXmlParser() {
        try {
            this.jaxbContext = JAXBContext.newInstance(OembedResponse.class);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public OembedResponse unmarshal(InputStream httpResponse) throws OembedException {
        try {
            return (OembedResponse) jaxbContext.createUnmarshaller().unmarshal(httpResponse);
        } catch (JAXBException e) {
            throw new OembedException(e);
        }
    }

    @Override
    public String marshal(OembedResponse oembedResponse) throws OembedException {
        try {
            final StringWriter out = new StringWriter();
            jaxbContext.createMarshaller().marshal(oembedResponse, out);
            out.flush();
            out.close();
            return out.toString();
        } catch (Exception e) {
            throw new OembedException(e);
        }
    }

    @Override
    public void marshal(OembedResponse oembedResponse, OutputStream outputStream) throws OembedException {
        try {
            jaxbContext.createMarshaller().marshal(oembedResponse, outputStream);
        } catch (Exception e) {
            throw new OembedException(e);
        }
    }
}